package util;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;

/**
 * 读取json文件的工具类
 *
 * @author xym
 * @since 2020/7/15
 */
public class JsonFileUtil {
    private JsonFileUtil() {
    }

    private volatile static JsonParser jsonParser;
    private static final Logger log = LoggerFactory.getLogger(JsonFileUtil.class);

    public static JsonObject read(String jsonFilePath) {
        if (jsonParser == null) {
            synchronized (JsonFileUtil.class) {
                if (jsonParser == null) {
                    jsonParser = new JsonParser();
                }
            }
        }

        JsonObject jsonObject = null;
        try {
            log.info("开始加载文件 - {}", jsonFilePath);
            long start = System.currentTimeMillis();

            jsonObject = (JsonObject) jsonParser.parse(new BufferedReader(new FileReader(jsonFilePath)));

            long end = System.currentTimeMillis();
            log.info("加载文件完成, 耗时{} ms", (end - start));
        } catch (FileNotFoundException e) {
            log.error("读取文件失败 - {}", jsonFilePath);
            e.printStackTrace();
        }
        return jsonObject;
    }
}
